package com.jiang.entity;

import com.jiang.operator.BlockChain;
import com.jiang.operator.BlockUtils;
import com.jiang.operator.RSAUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class RpcThread extends Thread{
    private static final Logger LOGGER = LoggerFactory.getLogger(RpcThread.class);
    private Socket socket;
    public String res;//回复
    public String req;//请求
    public Map<String, String> mapStr;//生产者，生产者签名，用密钥加密自己的信息


    public RpcThread(Socket socket) {
        this.socket = socket;
        //生成密钥对
        this.mapStr = RSAUtils.createKeys(1024);
    }

    public void run(){
        try {
            req = null;
            res = null;
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String input;
            out.println("[    Welcome RPC Daemon     ]");
            while((input = in.readLine()) != null){
                if("HELP".equalsIgnoreCase(input)){
                    out.println("###############################COMMANDS###############################");
                    out.println("#        1)getinfo      -Gets blockchain informations.               #");
                    out.println("#        2)send <vac>   -Write <vac> to blockchain                   #");
                    out.println("######################################################################");
                }else {
                    req = input;
                    while (res == null){
                        TimeUnit.MILLISECONDS.sleep(25);
                    }
                    out.println(res);
                    req = null;
                    res = null;
                }
            }
        } catch (Exception e) {
            LOGGER.error("An RPC client has disconnected");
        }
    }

    public void generateBlock(String[] vac){
        BlockUtils.generateBlock(BlockChain.blockChain.get(BlockChain.blockChain.size()-1), vac);
    }
}
